#!/usr/bin/env python3
"""
添加区域管理表的迁移脚本
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.models import db, Area
from wsgi import create_app

def migrate():
    """执行迁移"""
    # 设置正确的数据库路径
    os.environ['DATABASE_URL'] = 'sqlite:////home/gd/dispatch-system/backend/instance/dispatch_system.db'
    app = create_app()
    
    with app.app_context():
        try:
            # 创建区域表
            db.create_all()
            
            # 检查是否已有区域数据
            if Area.query.count() == 0:
                print("创建默认区域数据...")
                
                # 创建默认区域
                default_areas = [
                    Area(name='A区域', description='A区域维修范围'),
                    Area(name='B区域', description='B区域维修范围'),
                    Area(name='C区域', description='C区域维修范围'),
                ]
                
                for area in default_areas:
                    db.session.add(area)
                
                db.session.commit()
                print(f"成功创建 {len(default_areas)} 个默认区域")
            else:
                print("区域表已存在数据，跳过默认数据创建")
                
            print("区域表迁移完成")
            
        except Exception as e:
            print(f"迁移失败: {e}")
            db.session.rollback()
            raise

if __name__ == '__main__':
    migrate()